package fr.enseirb.mycub.activity;

import java.util.ArrayList;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObservable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
import com.slidingmenu.lib.app.SlidingMapActivity;

import fr.enseirb.mycub.PrefManager;
import fr.enseirb.mycub.R;
import fr.enseirb.mycub.activity.component.LocationServiceComponent;
import fr.enseirb.mycub.activity.component.MapOverlayComponent;
import fr.enseirb.mycub.activity.component.layer.BikeLayer;
import fr.enseirb.mycub.activity.component.layer.BusLayer;
import fr.enseirb.mycub.activity.component.layer.InternetLayer;
import fr.enseirb.mycub.activity.component.layer.ParkingLayer;
import fr.enseirb.mycub.activity.component.layer.TramLayer;
import fr.enseirb.mycub.activity.component.slidingmenu.SampleAdapter;
import fr.enseirb.mycub.activity.component.slidingmenu.SlidingMenuItem;
import fr.enseirb.mycub.service.ILocationServiceListener;
import fr.enseirb.mycub.service.UpdateService;
import fr.enseirb.mycub.utils.ActivityHelper;
import fr.enseirb.mycub.utils.Constants;
import fr.enseirb.mycub.utils.DetachableResultReceiver;
import fr.enseirb.mycub.utils.IActivityHelper;

public class MainActivity extends SlidingFragmentActivity implements IActivityHelper,
ILocationServiceListener, DetachableResultReceiver.Receiver{

	protected ListFragment mFrag;

	private final static int SEARCH = 0;
	private final static int BUS = SEARCH + 1;
	private final static int TRAMWAY = BUS + 1;
	private final static int BIKE = TRAMWAY + 1;
	private final static int PARKING = BIKE + 1;
	private final static int INTERNET = PARKING + 1;
	private final static int SETTINGS = INTERNET + 1;

	private static ProgressDialog mPdialog = null;
	private static ActivityHelper mActivityHelper = null;
	protected static DetachableResultReceiver mReceiver = null;
	MapOverlayComponent mapOverlayComponent;
	ListView listView;

	private UpdateThread updateThread = null;

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_layout);
		// set the Behind View
		setBehindContentView(R.layout.simple_list);
		ArrayList<SlidingMenuItem> items = new ArrayList<SlidingMenuItem>();
		items.add(new SlidingMenuItem(SEARCH, getString(R.string.search_), android.R.drawable.ic_menu_search,false,false){
			@Override
			protected void onClickImpl(){
			}
		});
		items.add(new SlidingMenuItem(BIKE, getString(R.string.bike_), R.drawable.velo,true,false){
			@Override
			protected void onClickImpl(){
				if(checked)mapOverlayComponent.addLayer(new BikeLayer(mapOverlayComponent));
				else mapOverlayComponent.removeLayer(BikeLayer.class);
			}
		});
		items.add(new SlidingMenuItem(TRAMWAY, getString(R.string.tramway_), R.drawable.tramway,true,false){
			@Override
			protected void onClickImpl(){
				if(checked)mapOverlayComponent.addLayer(new TramLayer(mapOverlayComponent));
				else mapOverlayComponent.removeLayer(TramLayer.class);
			}
		});
		items.add(new SlidingMenuItem(BUS,getString(R.string.bus_), R.drawable.bus,true,false){
			@Override
			protected void onClickImpl(){
				if(checked)mapOverlayComponent.addLayer(new BusLayer(mapOverlayComponent));
				else mapOverlayComponent.removeLayer(BusLayer.class);
			}
		});
		
		items.add(new SlidingMenuItem(PARKING, getString(R.string.parkings_), R.drawable.parking,true,false){
			@Override
			protected void onClickImpl(){
				if(checked)mapOverlayComponent.addLayer(new ParkingLayer(mapOverlayComponent));
				else mapOverlayComponent.removeLayer(ParkingLayer.class);
			}
		});
		
		items.add(new SlidingMenuItem(INTERNET, getString(R.string.internets_), R.drawable.internet,true,false){
			@Override
			protected void onClickImpl(){
				if(checked)mapOverlayComponent.addLayer(new InternetLayer(mapOverlayComponent));
				else mapOverlayComponent.removeLayer(InternetLayer.class);
			}
		});
		
		items.add(new SlidingMenuItem(SETTINGS, getString(R.string.preferences_), android.R.drawable.ic_menu_preferences,false,false){
			@Override
			protected void onClickImpl(){
				Intent intent = new Intent(MainActivity.this, SettingsPreferencesActivity.class);
				startActivity(intent);
			}
		});
		
		final SampleAdapter adapter = new SampleAdapter(this, items);
		
		listView = (ListView) findViewById(android.R.id.list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i("ON CLICK","position "+position);
				SlidingMenuItem item = (SlidingMenuItem) view.getTag();
				item.onClick(false);
				adapter.notifyDataSetChanged();
			}
		});
		// customize the SlidingMenu
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.actionbar_home_width);

		mReceiver = DetachableResultReceiver.getInstance(new Handler());
		mActivityHelper = new ActivityHelper(this);
		//mActivityHelper.setupActionBar(getString(R.string.station_map));
		mPdialog = new ProgressDialog(this);
		mapOverlayComponent = new MapOverlayComponent(this, savedInstanceState);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			Log.i("MainActivity", "toggle()");
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		mapOverlayComponent.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mapOverlayComponent.onResume(this);
		mReceiver.setReceiver(this);
		updateThread = new UpdateThread();
		updateThread.setRunning(true);
		updateThread.start();
		loadDefaultLayer();;

	}

	@Override
	protected void onPause() {
		updateThread.setRunning(false);
		mapOverlayComponent.onPause();
		mReceiver.clearReceiver();
		super.onPause();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapOverlayComponent.onSaveInstanceState(outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportActionBar().setTitle(R.string.map_);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		menu.add("My Position")
		.setIcon(R.drawable.gps).setOnMenuItemClickListener(myPositionOnClickListener)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		menu.add("Refresh")
		.setIcon(R.drawable.ic_action_refresh).setOnMenuItemClickListener(refreshOnClickListener)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		menu.add("Layer")
		.setIcon(R.drawable.layer).setOnMenuItemClickListener(layerOnClickListener)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		return super.onCreateOptionsMenu(menu);
	}

	private OnMenuItemClickListener myPositionOnClickListener = new OnMenuItemClickListener() {
		public boolean onMenuItemClick(MenuItem item) {
			Log.i("Submenu", "my Position");
			mapOverlayComponent.zoomAndCenterOnMyPosition();
			return false;
		}
	};

	private OnMenuItemClickListener layerOnClickListener = new OnMenuItemClickListener() {
		public boolean onMenuItemClick(MenuItem item) {
			Log.i("Submenu", "layer");
			mapOverlayComponent.swapBetweenSateliteAndMapView();
			return false;
		}
	};

	private OnMenuItemClickListener refreshOnClickListener = new OnMenuItemClickListener() {
		public boolean onMenuItemClick(MenuItem item) {
			Log.i("Submenu", "refresh");
			Intent intent = new Intent(MainActivity.this, UpdateService.class);
			intent.setAction(UpdateService.ACTION_FORCED_REFRESH);
			startService(intent);
			return false;
		}
	};

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case R.id.progress:
			mPdialog.setCancelable(false);
			return mPdialog;
		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		//getActivityHelper().onPrepareDialog(id, dialog);
		super.onPrepareDialog(id, dialog);
	}

	@Override
	public void onLocationChanged(Location location, boolean firstFix) {
		mapOverlayComponent.onLocationChanged(this,location,firstFix);
	}

	@Override
	public void onStationsUpdated() {
		mapOverlayComponent.onStationsUpdated(this);
	}

	public void showProgressDialog(String title, String message) {
		mPdialog.setTitle(title);
		mPdialog.setMessage(message);
		if (!mPdialog.isShowing())
			showDialog(R.id.progress);
	}

	public void dismissProgressDialog() {
		// onListUpdated();
		if (mPdialog.isShowing())
			//			dismissDialog(R.id.progress);
			mPdialog.dismiss();
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		mActivityHelper.onReceiveResult(resultCode, resultData);
	}

	@Override
	public void onLocationProvidersChanged(int id) {
		if (!isFinishing()) {
			showDialog(id);
		}
	}

	@Override
	public ActivityHelper getActivityHelper() {
		return mActivityHelper;
	}

	private class UpdateThread extends Thread{

		boolean running = false;
		Intent refresh;

		public UpdateThread(){
			createIntent();
		}

		private void createIntent(){
			refresh = new Intent(MainActivity.this, UpdateService.class);
			refresh.setAction(UpdateService.ACTION_REFRESH);
		}

		public void setRunning(boolean run) {
			running = run;
		}

		@Override
		public void run() {
			while(running){
				Log.i("Thread", "run update");
				if(refresh == null)createIntent();
				startService(refresh);
				try {
					sleep(UpdateService.minIntervalUntilNextUpdate);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void loadDefaultLayer(){
		Log.i(this.getClass().getCanonicalName(), "---> restoring checked layers");
		for(int i = 0; i < SETTINGS; i++){
			SlidingMenuItem item =  (SlidingMenuItem) listView.getAdapter().getItem(i);
			if(PrefManager.mgr.getBoolean(Constants.PREF_SLIDING_MENU_ITEM+item.id, false)){
				item.onClick(true);
				((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
			}
		}
	}

}
